<template>
  <view :id="elId" ref="ui-row" :style="style" :class="tagClass" @click="onClick">
    <slot />
  </view>
</template>

<script>
  export default {

    props: {
      type: String,
      align: String,
      justify: String,
      gutter: {
        type: [Number, String],
        default: 0
      }
    },
    provide() {
      return {
        row: this
      }
    },
    data() {
      const elId = `Uni_${Math.ceil(Math.random() * 10e5).toString(36)}`
      return {
        elId,
        width: 0
      }
    },
    created() {
      this.children = []
    },
    mounted() {
      this.$nextTick(() => {
        this.init()
      })
    },
    methods: {
      onClick: function onClick(event) {
        this.$emit('click', event);
      },
      init() {
        setTimeout(() => {
          this._getSize((width) => {
            this.children.forEach((item, index) => {
              item.resetWidth(this.width)
            })
          })
        }, 50)
      },
      _getSize(fn) {
        // #ifndef APP-NVUE
        uni.createSelectorQuery()
          .in(this)
          .select(`#${this.elId}`)
          .boundingClientRect()
          .exec(ret => {
            this.width = parseInt((ret[0].width - 1) )
            
            fn(this.width)
          })
        // #endif
        // #ifdef APP-NVUE
        dom.getComponentRect(this.$refs['ui-row'], (ret) => {
          this.width = parseInt((ret.size.width - 1))
          fn(this.width)
        })
        // #endif
      }
    },


    computed: {
      style() {
        var margin = "-" + Number(this.gutter) / 2 + "upx";
        return this.gutter ? {
          marginLeft: margin,
          marginRight: margin
        } : {};
      },
      tagClass() {
        var align = this.align,
          justify = this.justify;
        var flex = this.type === 'flex';
        return `${flex ? 'ui-row--flex' : 'ui-row'} ${flex && align ? ('ui-row--align-' + align) : ''} ${flex && justify ? ('ui-row--justify-' + justify) : ''}`;
      },
    }
  }
</script>

<style lang="scss" scoped>
  .ui-row {
    position: relative;

    &::after {
      display: table;
      clear: both;
      content: '';
    }

    &--flex {
      display: flex;

      &::after {
        display: none;
      }
    }

    &--justify-center {
      justify-content: center;
    }

    &--justify-end {
      justify-content: flex-end;
    }

    &--justify-space-between {
      justify-content: space-between;
    }

    &--justify-space-around {
      justify-content: space-around;
    }

    &--align-center {
      align-items: center;
    }

    &--align-bottom {
      align-items: flex-end;
    }
  }
</style>
